<template>
  <div class="management" v-if="addBool == 1">
    <div style="background-color: #fff;">
      <el-form :model="queryForm" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="客户电话:">
              <el-input v-model="queryForm.customerId" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户姓名:">
              <el-input v-model="queryForm.customerName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属阶段:">
              <el-select v-model="queryForm.stage" placeholder="请选择">
                <el-option v-for="item in stageList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="订单状态:">
              <el-select v-model="queryForm.orderStatus" placeholder="请选择">
                <el-option v-for="item in orderStatusList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button plain @click="query">查询</el-button>
            <el-button plain @click="reset">重置</el-button>
          </el-col>
        </el-row>

      </el-form>
    </div>
    <div style="background-color: #fff;">
      <el-button @click="addCustomer" type="primary" style="margin: 10px;">新增</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%;" ref="tableRef">
      <el-table-column align="center" fixed prop="customerId" label="客户电话" width="90" />
      <el-table-column align="center" fixed prop="customerName" label="客户姓名" width="90" />
      <el-table-column align="center" prop="school" label="客户学校" width="120" />
      <el-table-column align="center" prop="speciality" label="客户专业" width="120" />
      <el-table-column align="center" prop="stage" label="所属阶段" width="80" />
      <el-table-column align="center" prop="money" label="金额" width="60" />
      <el-table-column align="center" prop="deposit" label="已收定金" width="80" />
      <el-table-column align="center" prop="completedMoney" label="已收尾款" width="80" />
      <el-table-column align="center" prop="degree" label="学位" width="70" />
      <el-table-column align="center" prop="thesisTitle" label="论文题目" width="100" />
      <el-table-column align="center" prop="orderStatus" label="订单状态" width="80" />
      <el-table-column align="center" prop="fileName" label="客户文件" width="80" />
      <el-table-column align="center" prop="director" label="负责人" width="90" />
      <el-table-column align="center" prop="followUp" label="跟进人" width="90" />
      <el-table-column align="center" prop="check" label="查重" width="60" />
      <el-table-column align="center" prop="notes" label="客户备注" />
      <el-table-column align="center" prop="accountPassword" label="账号密码" />
      <el-table-column align="center" prop="website" label="网址链接" />
      <el-table-column align="center" fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleClick(scope.row)">
            修改
          </el-button>
          <el-button v-if="userStore.userdepartment == '管理员'" link type="primary" size="small"
            @click="delUserClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination @current-change="currentChange" :current-page="pageing.page" :page-size="pageing.size"
        :total="pageing.total" style="float: right" layout=" prev, pager, next" />
    </div>
    <el-dialog v-model="editDialogVisible" title="修改客户" width="800" :before-close="handleClose" align-center>
      <el-form :model="userForm" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item prop="customerId" label="客户电话:">
              <el-text>{{ userForm.customerId }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="customerName" label="客户姓名:">
              <el-text>{{ userForm.customerName }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="school" label="客户学校:">
              <el-text line-clamp="2">{{ userForm.school }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="speciality" label="客户专业:">
              <el-text>{{ userForm.speciality }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item prop="followUp" label="跟进人:">
              <el-text>{{ userForm.followUp }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="director" label="负责人:">
              <el-text>{{ userForm.director }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="stage" label="所属阶段:">
              <el-text>{{ userForm.stage }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="orderStatus" label="订单状态:">
              <el-text>{{ userForm.orderStatus }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item prop="money" label="金额:">
              <el-input v-model="userForm.money" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="deposit" label="己收定金:">
              <el-input v-model="userForm.deposit" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="completedMoney" label="己收尾款:">
              <el-input v-model="userForm.completedMoney" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="check" label="查重:">
              <el-input v-model="userForm.check" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="degree" label="学位">
              <el-radio-group v-model="userForm.degree">
                <el-radio value="带学位">带学位</el-radio>
                <el-radio value="不带学位">不带学位</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="accountPassword" label="账号密码:">
              <el-input v-model="userForm.accountPassword" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="website" label="网址链接:">
              <el-input v-model="userForm.website" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上传客户文件" prop="filePath">
              <el-upload v-model:file-list="fileList" ref="uploadRef" class="upload-demo"
                action="http://192.168.168.224:8880/api/commerce/v2/client/upload" :headers="headersObj"
                :auto-upload="false" :on-success="handleSuccess" :on-error="handleError" :limit="1"
                :on-exceed="handleExceed" :on-remove="handleRemove" :on-change="handleChange">
                <el-button type="primary">选择文件</el-button>
                <div class="el-upload__tip">
                  仅支持 jpg/png 文件，且不超过 500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="notes" label="客户备注">
              <el-input v-model="userForm.notes" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="editUserClick(userForm)">
            提交
          </el-button>
          <el-button @click="cancellClick">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <div v-else-if="addBool == 2">
    <ManagEment :addRef="addBool" @addrefClick="newValue => addBool = newValue" />
  </div>
</template>

<script setup name="information">
import { ref, reactive, onMounted, computed, watch, getCurrentInstance, onActivated } from 'vue'
import { ElMessageBox, ElNotification } from 'element-plus'
import ManagEment from "./components/management.vue";
import { customerList, customerEdit, customerDel } from "@/api/modules/upload";
import { useUserStore } from "@/stores/modules/user"; // 导入用户状态管理store
// el-table支持鼠标横向拖拽滚动
const { proxy } = getCurrentInstance()
const tableRef = ref()
nextTick(() => {
  if (tableRef.value) {
    proxy.$dragTable(tableRef)
  }
})
const userStore = useUserStore(); // 获取用户状态管理store实例
const headersObj = {
  "Authorization": 'Bearer ' + userStore.token,    // JWT认证，携带token
}
// 新增页面控制值
let addBool = ref(1);
const editDialogVisible = ref(false)
// 定义监听属性
watch(
  () => addBool,
  (newValue, oldValue) => {
    if (newValue.value == 1) {
      customerFun();
    }
  },
  {
    deep: true
  }
)
// 客户修改
const userForm = reactive({
  customerId: '',
  customerName: '',
  school: '',
  speciality: '',
  stage: '',
  money: '',
  deposit: '',
  completedMoney: '',
  degree: '',
  thesisTitle: '',
  orderStatus: '',
  director: '',
  followUp: '',
  notes: '',
  accountPassword: '',
  website: '',
  check: '',
  fileName: "",
  filePath: "",
})
const pageing = ref({
  total: 0,
  page: 1,
  size: 5,
})

// 客户展示表格
const tableData = reactive([]);
const tableDataed = reactive([])
// 所属阶段列表
const stageList = reactive([
  {
    value: '选题',
    label: '选题',
  },
  {
    value: '开题',
    label: '开题',
  },
  {
    value: '初稿',
    label: '初稿',
  },
  {
    value: '定稿',
    label: '定稿',
  },
])
// 订单状态列表
const orderStatusList = reactive([
  {
    value: '计划',
    label: '计划',
  },
  {
    value: '已结束',
    label: '已结束',
  },
])
// 查询表单
const queryForm = reactive({
  customerId: '',
  customerName: '',
  stage: '',
  orderStatus: '',
})
// 选择第几页
const currentChange = (val) => {
  console.log("翻页，当前为第几页", val);
  tableData.length = 0;
  for (let i = 0; i < 5; i++) {
    console.log(tableDataed[(val - 1) * 5 + i]);
    if (tableDataed[(val - 1) * 5 + i]) {
      tableData.push(tableDataed[(val - 1) * 5 + i])
    }
  }
  pageing.value.page = val;
  console.log(pageing.value.total);
}
// 查询
const query = async () => {
  const { data } = await customerList({ ...queryForm });
  tableDataed.length = 0
  Object.assign(tableDataed, data);
  pageing.value.total = data.length;
  currentChange(1)
}
// 重置
const reset = () => {
  const obj = {
    customerId: '',
    customerName: '',
    stage: '',
    orderStatus: '',
  }
  Object.assign(queryForm, obj);
  customerFun();
}

// 缓存文件上传
const uploadRef = ref(null);
// 显示已上传的客户文件信息
const fileList = ref([]);
// 修改取消
const cancellClick = () => {
  editDialogVisible.value = false;
  fileList.value = [];
  // fileList.length = 0;
}
// 默认加载客户列表
onActivated(() => {
  console.log(11111);
  customerFun();
})
// 1.执行获取用户信息接口
const customerFun = async () => {
  const { data } = await customerList();
  Object.assign(tableDataed, data);
  pageing.value.total = data.length;
  currentChange(1)
}

// 打开修改页面
const handleClick = (user) => {
  console.log(user)
  console.log(fileList);
  editDialogVisible.value = true;
  if (!user.fileName) {
    fileList.value = [];
    Object.assign(userForm, user);
    return;
  }
  fileList.value = [{ "name": user.fileName, "url": user.filePath }];
  Object.assign(userForm, user);
}
// 修改成员提交
const editUserClick = async (user) => {
  if (fileList.value.length == 0) {
    // 删除无上传
    const oldFilepath = userForm.filePath;
    const oldFilename = userForm.fileName;
    userForm.fileName = "";
    userForm.filePath = "";
    handleSuccessFun({ oldFilepath, oldFilename })
    return;
  } else if (fileList.value[0].name == user.fileName) {
    // 无修改文件上传提交
    handleSuccessFun()
    return;
  } else {
    // 删除文件上传提交
    const filePath = await uploadRef.value.submit()
  }
}
// 上传成功后的处理修改提交
const handleSuccess = async (response, file, fileList) => {
  const oldFilepath = userForm.filePath;
  const oldFilename = userForm.fileName;
  userForm.filePath = response.data.filepath;
  userForm.fileName = response.data.filename;
  handleSuccessFun({ oldFilepath, oldFilename })
};
// 监听上传时触发
const handleChange = (files) => {
  fileList.value = [{ "name": files.name, "url": "" }];
}
// 文件列表删除触发
const handleRemove = (file, uploadFiles) => {
  fileList.value = [];
}
// 上传失败后的处理 
const handleError = (error, file, fileList) => {
  console.error(error);
  ElNotification({
    title: "文件上传",
    message: "文件上传失败",
    type: "error",
    duration: 1000
  })
};
// 限制只能上传一个文件
const handleExceed = (files, fileList) => {
  ElNotification({
    title: "文件上传",
    message: "只允许上传一个文件,如需上传最新文件需删除原文件",
    type: "error",
    duration: 2000
  })
}
// 点击跳转新增修改
const addCustomer = () => {
  addBool.value = 2;
}
// 删除客户
const delUserClick = async (user) => {
  const data = await customerDel({
    "customerId": user.customerId,
    "fileName": user.fileName,
    "filePath": user.filePath,
  });

  if (data.code == 200) {
    ElNotification({
      title: "删除成员",
      message: "用户删除成功",
      type: "success",
      duration: 1000
    });
    customerFun();
  } else {
    ElNotification({
      title: "删除成员",
      message: "用户删除失败",
      type: "error",
      duration: 1000
    });
  }
}
// 空白取消
const handleClose = (done) => {
  ElMessageBox.confirm('您确定要关闭此对话框吗?')
    .then(() => {
      fileList[0] = {
        name: null,
        url: null
      };
      done()
    })
    .catch(() => {
      // catch error
    })
}
// 封装修改调接口
const handleSuccessFun = async (obj) => {
  let data;
  if (obj) {
    data = await customerEdit({ ...userForm, ...obj });
  } else {
    data = await customerEdit({ ...userForm });
  }
  if (data.code == 200) {
    cancellClick()
    ElNotification({
      title: "客户信息",
      message: "客户信息修改成功",
      type: "success",
      duration: 1000
    });
    customerFun();
  } else {
    cancellClick();
    ElNotification({
      title: "客户信息",
      message: "客户信息修改失败",
      type: "error",
      duration: 1000
    });
  }
}
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>